package com.bsh.pay;

import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsh.service.PaymentService;


/**
 * 微信回调
 * 
 * @author jane
 * @since 0.0.1
 * 
 */
@Controller
public class WebHookWeiXinController {
    private static Logger log = LoggerFactory.getLogger(WebHookWeiXinController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    HttpSession session;
    @Autowired
    PaymentService paySer;
     
    @RequestMapping(value = "/pay/v1/wx/webhook")
    public ModelAndView weiXinWebHook() throws Exception {
   
    	response.setContentType("text/html; charset=utf-8");
    	String fail = "fail";
    	String success = "success";
    	StringBuffer json = new StringBuffer();
        String line = null;

        try {
            request.setCharacterEncoding("utf-8");
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sign = null;
        String timeStamp = null;
        if(!StringUtils.isEmpty(json.toString())){
//        	 JSONObject jsonObj = JSONObject.fromObject(json.toString());
        	 JSONObject jsonObj = JSON.parseObject(json.toString());
        	 
        	 //进service
        	 Integer res = paySer.backWxPayment(jsonObj);
        	 if( res>0){
        		 response.getWriter().println(success);
        		 return null;
        	 }else{
        		 log.error("webHook_error:回调结果fail["+jsonObj.getString("transaction_id")+"]");
        		 response.getWriter().println(fail);
        		 return null;
        	 }
        	 
        	 //end v0.0.1 
        	  
             /*
        	 sign = jsonObj.getString("sign");
             timeStamp = jsonObj.getString("timestamp");
             if( timeStamp == null || sign == null){
            	 return null;
             }
             boolean status = verifySign(sign, timeStamp);
             if (status) { //验证成功
            	 // 开始业务
            	 if(jsonObj.getString("transactionType").equals("PAY") ) {
            		    //付款信息
            		    //支付状态是否变为支付成功
            		    //$result = $msg['tradeSuccess'];
            		    String channelType = jsonObj.getString("channelType");
            		    switch (channelType) {
						case "WX":
							String outTradeNo = jsonObj.getString("out_trade_no");//商家内部交易号

							String tradeNo = jsonObj.getString("transaction_id");  //微信交易号
							//交易状态
				
							break;

						}
            	 }           	 
            	 response.getWriter().println(success);
            	 
             }else{
            	 response.getWriter().println(fail);
            	 return null;
             }
             */
        }
       
		response.getWriter().println("Thanks");
		return null;
        
    }
    
    private boolean verifySign(String sign, String timeStamp) {
    	 String appId = "498097f8-cf0f-463c-91d0-3a5f1988d0a1";
         String appSecret = "xxxx";
    	 return verify(sign, appId + appSecret,timeStamp, "UTF-8");
	}
    private boolean verify(String sign, String text, String key, String inputCharset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, inputCharset));
        //log.info("mysign:" + mysign);
        long timeDifference = System.currentTimeMillis() - Long.valueOf(key);
        //log.info("timeDifference:" + timeDifference);

        //时间 300000 有效期
        return mysign.equals(sign) && timeDifference <= 300000;
    }
   private byte[] getContentBytes(String content, String charset) {
       if (charset == null || "".equals(charset)) {
           return content.getBytes();
       }
       try {
           return content.getBytes(charset);
       } catch (UnsupportedEncodingException e) {
           throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
       }
   }
   
}
